// pages/position/hourly/add/add.js
import uploadImg from '../../../../utils/uploadImg.js'
import { onRecord } from '../../../../utils/integral-record.js'
import {
  edu,
  street,
  reward,
  clearingWay,
  workExp
} from '../../../../utils/base-data.js'
import {
  $wuxSelect,
  $wuxDialog
} from '../../../../wux-components/index'
import {
  getLocation
} from '../../../../utils/common.js'
import { payStatus} from '../../../../utils/payStatus.js'
import {
  searchPosition
} from '../../../../utils/position.js'
const config = getApp().globalData.config
const T = getApp().globalData.T
let token = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
    platform: '',
    isEdit: false,
    positionEditId:-1, // 编辑时用
    position:'',
    address:'',
    salary:'',
    posDes:'',
    isRedpacket:false,
    redpacketCount:'',
    singleRedpacketMoney:'',
    isHide: true,
    workCompany:'',
    workCompanyId:0,

    workStart:'请选择',
    workEnd:'请选择',
    workTime:'请选择',
    startTimeDate: '00:00', // 开始时间段
    endTimeDate: '01:00', // 结束时间段
    payMethod:{title:'请选择'},
    workExp:{title:'请选择'},
    eduExp:{title:'请选择'},
    street:{title:'请选择'},
    employmentType:{title:'请选择'},
    eduExp:{title:'请选择'},

    subscribeTime1: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
    subscribeTime2: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
    clearWayArray: [{ title: '日结', value: 0 }, { title: '周结', value: 1 }, { title: '月结', value: 2 }],

    templateImg: '/resource/image/add_post_img.png',
    positionId: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.positionEditId = Number(options.id);
    if (getApp().globalData.platform == 'ios') {
      this.setData({platform: 'ios'});
    }
    this.setData({
      isEdit: options.origin == 'edit' ? true : false
    })
    if (options.id) {
      wx.setNavigationBarTitle({
        title: '编辑小时工',
      })
    }
  },  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.isOpenUploadImg) return;
    token = getApp().globalData.token;
    this.showMap();
    if (this.data.isEdit) {
      this.getDetail();
      this.getRefundInfo();
    }
  },

  showMap(lt, la) {
    this.setData({
      longitude: lt || 116.397726,
      latitude: la || 39.903767,
      markers: [{
        iconPath: "/resource/image/marker.png",
        id: 0,
        longitude: lt || 116.397726,
        latitude: la || 39.903767,
        width: 20,
        height: 30
      }]
    })
  },

  onUpdateTemplate() {
    let that = this;
    this.data.isOpenUploadImg = true;
    uploadImg(that, 'image', 'resumeImgUpload')
      .then((res) => {
        that.setData({
          templateImg: res,
          isOpenUploadImg: false
        })
      })
  },

  // 获取退款情况
  getRefundInfo() {
    T.req({
      url: config.api + 'position_hourly/refund_info',
      method: 'GET',
      data: {
        positionId: this.data.positionEditId,
        token: token
      },
      success: (res) => {
        this.data.redpacketOrderId = res.orderId; // 订单号
        if (res.isNeedRefund) { // 能退款
          this.setData({ toRefund: true})
        } else { //不能退款
          if (res.refund == 0) { // 退款审核中
            this.setData({ isRefunding: true});
          }
          if (res.refund == 1) { // 退款审核通过
            this.setData({ passRefund: true });
          }
          if (res.refund == 2) { // 退款失败
            this.setData({ againRefund: true, failRefundText:res.refundNote });
          }
          if (res.refund == 3) {
            this.setData({ successRefund: true})
          }
        }
      }
    })
  },

  getDetail() {
    T.req({
      loadTitle: '加载中...',
      url: config.api + 'position_hourly/' + this.data.positionEditId,
      method: 'GET',
      data: {
        token: token
      },
      success: (res) => {
        this.setData({
          position: res.name,
          salary: res.salary,
          payMethod: { title: clearingWay[res.clearingWay].title, value: res.clearingWay},
          workStart: T.formatTime(res.startWorkDate, '-'),
          workEnd: T.formatTime(res.endWorkDate	, '-'),
          workTime: res.startWorkTime + '-' + res.endWorkTime,
          workExp: { title: res.candidateRequire, value: res.candidateRequireId},
          eduExp: { title: edu[res.education].title, value: res.education},
          ['street.title']: res.street,
          address: res.address,
          posDes: res.description,
          employmentType: { title: res.employmentType == 1 ? '代招':'直招', value: res.employmentType},
          workCompany: res.workCompany,
          templateImg: res.entrustPhoto || this.data.templateImg,
          workCompanyId: res.workCompanyId,
          isRedpacket: res.redPacket.totalMoney ? true : false,
          isSetedRedpacket: res.redPacket.totalMoney ? true : false,
          isSoldout: res.usable
        });

        getLocation(res.address).then((res) => {
          if (JSON.stringify(res) == '{}') return;
          this.setData({ location: res.location })
          let lt = res.location.split(',')[0];
          let la = res.location.split(',')[1];
          this.showMap(lt, la);
        });

        if (this.data.isRedpacket) { // 有设置红包
          this.setData({
            redpacketCount: res.redPacket.quantity,
            singleRedpacketMoney: res.redPacket.money,
            usedQuantity: res.redPacket.usedQuantity,
            residueMoney: res.redPacket.residueMoney,
            redPacketTotal: res.redPacket.totalMoney,
            isDisableInputRedpack: res.redPacket.residueMoney>0? true: false
          })
        } 
      },
      
    })
  },

  onInputPosition(e) {
    this.setData({
      position: e.detail.value
    });
    if (!e.detail.value) return;
    searchPosition(e.detail.value, 1).then(res => {
      this.setData({ companyList: res, isOpen: true })
    })
  },

  onSelectCompany(e) {
    let name = e.currentTarget.dataset.name;
    this.setData({ position: name, isOpen: false });
  },

  onClosePosition() {
    this.setData({
      isOpen: false
    })
  },

  onInputSalary(e) {
    this.setData({salary: e.detail.value});
  },

  onChangeWorkStart(e) {
    this.setData({workStart: e.detail.value});
  },
  onChangeWorkEnd(e) {
    this.setData({ workEnd: e.detail.value});
  },

  onClickWorkTime(){
    this.setData({ isHide: false, isShowMap: true, isShowPosDes: true });
  },

  onSelectTimesCancel() {
    this.setData({ isHide: true, isShowMap: false, isShowPosDes: false });
  },

  onSelectTimesConfirm() {
    const _st = this.data.startTimeDate;
    const _et = this.data.endTimeDate;
    if (_st == _et) {
      T.toast({ id: '#toast', text: '开始结束工作时间段不能一样' });
      return;
    }
    this.setData({
      isHide: true,
      workTime: _st + ' - ' + _et,
      isShowMap: false, 
      isShowPosDes: false
    });
  },

  onSelectTimesChange(e) {
    const val = e.detail.value;
    this.setData({
      startTimeDate: this.data.subscribeTime1[val[0]] + ':00',
      endTimeDate: this.data.subscribeTime2[val[1]].trim() + ':00'
    });
  },

  onClickPayMethod() {
    this.setData({ isShowMap: true, isShowPosDes: true})
    $wuxSelect('#wux-select-payMethod').open({
      value: '',
      options: this.data.clearWayArray,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value2: value,
            payMethod: options[index],
            isShowMap: false, 
            isShowPosDes: false
          })
        }
      },
      onCancel: () => {
        this.setData({
          isShowMap: false,
          isShowPosDes: false
        })
      }
    });
  },

  onClickWorkExp() {
    this.setData({ isShowMap: true, isShowPosDes: true })
    $wuxSelect('#wux-select-workExp').open({
      value: '',
      options: workExp,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value2: value,
            workExp: options[index],
            isShowMap: false,
            isShowPosDes: false
          })
        }
      },
        onCancel: () => {
          this.setData({
            isShowMap: false,
            isShowPosDes: false
          })
        }
    });
  },

  onClickEduExp() {
    this.setData({ isShowMap: true, isShowPosDes: true })
    $wuxSelect('#wux-select-eduExp').open({
      value: '',
      options: edu,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value2: value,
            eduExp: options[index],
            isShowMap: false,
            isShowPosDes: false
          })
        }
      },
      onCancel: () => {
        this.setData({
          isShowMap: false,
          isShowPosDes: false
        })
      }
    });
  },

  onClickStreet() {
    this.setData({ isShowMap: true, isShowPosDes: true })
    $wuxSelect('#wux-select-street').open({
      value: '',
      options: street,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value2: value,
            street: options[index],
            isShowMap: false,
            isShowPosDes: false
          })
        }
      },
      onCancel: () => {
        this.setData({
          isShowMap: false,
          isShowPosDes: false
        })
      }
    });
  },

  onInputAddress(e) {
    this.setData({
      address: e.detail.value
    });
    if (!e.detail.value) return;
    getLocation(e.detail.value).then((res) => {
      if (JSON.stringify(res) == '{}') return;
      this.setData({location: res.location})
      let lt = res.location.split(',')[0];
      let la = res.location.split(',')[1];
      this.showMap(lt, la);
    });
  },

  onInputPosDes(e) {
    this.setData({
      posDes: e.detail.value
    });
  },

  onClickEmploymentType() {
    this.setData({ isShowMap: true, isShowPosDes: true })
    $wuxSelect('#wux-select-employmentType').open({
      value: '',
      options: [{
        title: '直招',
        value: 0
      }, {
        title: '代招',
        value: 1
      }],
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value2: value,
            employmentType: options[index],
            isShowMap: false,
            isShowPosDes: false
          })
        }
      },
      onCancel: () => {
        this.setData({
          isShowMap: false,
          isShowPosDes: false
        })
      }
    });
  },


  onSelectRedpacket() {
    this.setData({
      isRedpacket: !this.data.isRedpacket
    });
    if (!this.data.isRedpacket) return ;
    T.getEleheight('#redpack', (res) => {
      wx.pageScrollTo({
        scrollTop: res.top,
        duration: 300
      })
    })
  },

  onInputRedpacketCount(e) {
    this.setData({
      redpacketCount: e.detail.value,
      redPacketTotal: (Number(this.data.singleRedpacketMoney) * Number(e.detail.value)).toFixed(2),
      isUpdatePay: Number(e.detail.value) > 0 ? true : false
    });
  },

  onInputSingleRedpacketMoney(e) {
    this.setData({
      singleRedpacketMoney: e.detail.value,
      redPacketTotal: (Number(e.detail.value) * Number(this.data.redpacketCount)).toFixed(2),
      isUpdatePay: Number(e.detail.value) > 0 ? true : false
    });
  },

  /**
   * 支付
   */
  onPay(obj) {
    return new Promise((resolve, reject) => {
      T.req({
        loadTitle: '支付中...',
        url: config.api + 'pay/wechat/tradepay?token=' + token,
        method: 'POST',
        data: {
          openid: getApp().globalData.openId,
          goodsId: this.data.positionId,
          goodsType: 2,
          body: '新增小时工职位{' + obj.positionName +'}',
          topUpType:0,
          redpack:{
            quantity: obj.packetAmount,
            money: obj.redPacket
          }
        },
        success: (res) => {
          wx.requestPayment({
            timeStamp: res.timeStamp,
            nonceStr: res.nonceStr,
            package: res.package,
            signType: res.signType,
            paySign: res.paySign,
            success: () => {
              resolve(res.outTradeNo);
              onRecord(res.outTradeNo);
            },
            fail: (err) => {
              console.log(err)
            }
          })
        }
      })
    });
  },

  /**
   * 操作小时工职位成功，跳转到职位列表
   */
  onHourlySucessChange() {
    var pages = getCurrentPages();
    let routes = 0;
    if (this.data.isEdit) {// 如果是从编辑跳转过来，返回跳转路由跳两级
      routes = 1;
    }
    routes = routes || 0
    console.warn('routes:' + routes);
    if (pages.length > 1) {
      //上一个页面实例对象
      var prePage = pages[pages.length - 2 - routes];
      prePage.data.hourlyList = [];
      prePage.getHourlyList();
      wx.navigateBack({
        delta: 1 + routes
      })
    }
  },

  /**
   * 新增小时工
   */
  onCreatePos(obj) {
    let reqParam = {
      positionId: 0,
      userHrId: obj.userId,
      positionName: obj.positionName,
      salary: obj.salary,
      startDate: obj.startWorkDate,
      endDate: obj.endWorkDate,
      startWorkTime: obj.startWorkTime,
      endWorkTime: obj.endWorkTime,
      clearingWay: obj.clearingWay,
      candidateRequireId: obj.candidateRequireId,
      education: obj.education,
      street: obj.street,
      address: obj.address,
      location: obj.location,
      description: obj.description,
      employmentType: obj.employmentType,
    }

    if (obj.employmentType == 1) {
      reqParam.workCompany = obj.workCompany;
      reqParam.workCompanyId = obj.workCompanyId;
      reqParam.entrustPhoto = obj.entrustPhoto;
    } else {
      reqParam.workCompany = '';
    }

    // 之前是否已经调用过新增接口-如果是，直接调支付
    if (this.data.isCreatePosition && this.data.isRedpacket) {
      this.onPay(obj).then((orderid) => {
        payStatus(orderid).then(() => {
          this.onHourlySucessChange();
        })
      })
      return ;
    }

    T.req({
      loadTitle: '请求中...',
      url: config.api + 'position_hourly?token=' + token,
      method: 'POST',
      data: reqParam,
      success: (res) => {
        this.data.isCreatePosition = true;
        this.data.positionId = res.positionHourlyId;
        if (this.data.isRedpacket) {
          this.onPay(obj).then((orderid) => {
            payStatus(orderid).then(() => {
              this.onHourlySucessChange();
            })
          })
        } else {
          T.toast({ id: '#toast', text: '发布成功', success: () => {
            this.onHourlySucessChange();
          } })
        }
      }
    })
  },

  getPublishValue() {
  return new Promise((resolve, reject) => {
    let obj = {};
    let startWorkTime = this.data.workTime.split('-')[0] || '';
    let endWorkTime = this.data.workTime.split('-')[1] || '';
    obj.positionName = this.data.position;
    obj.salary = this.data.salary;
    obj.startWorkDate = this.data.workStart;
    obj.endWorkDate = this.data.workEnd;
    obj.startWorkTime = T.trim(startWorkTime);
    obj.endWorkTime = T.trim(endWorkTime);
    obj.clearingWay = this.data.payMethod.title;
    obj.candidateRequireId = this.data.workExp.title;
    obj.education = this.data.eduExp.title;
    obj.street = this.data.street.title;
    obj.address = this.data.address;
    obj.description = this.data.posDes;
    obj.employmentType = this.data.employmentType.title;
   
    if (this.data.employmentType.value == 1) { // 代招
      obj.workCompany = this.data.workCompany;
      obj.entrustPhoto = this.data.templateImg;
    }
    
    let isError = false;
    for (const k in obj) {
      if (!obj[k] || obj[k] == '请选择') {
        isError = true;
      }
    }

    if (this.data.isRedpacket) {
      obj.packetAmount = Number(this.data.redpacketCount);
      obj.redPacket = Number(this.data.singleRedpacketMoney);
      if (!obj.packetAmount || !obj.redPacket) {
        isError = true;
      }
    } 
    if (!/^http/.test(obj.entrustPhoto) && this.data.employmentType.value == 1) {
      isError = true;
    }
    console.log(obj)
    if (isError) {
      T.toast({ id: '#toast', text: '还有选项没有填写或者选择,请检查' });
      return;
    }
    if (!this.data.isRedpacket) {
      obj.redPacket = 0;
      obj.packetAmount = 0;
    }
    obj.salary = Number(this.data.salary);
    obj.clearingWay = this.data.payMethod.value;
    obj.candidateRequireId = Number(this.data.workExp.value);
    obj.education = this.data.eduExp.value;
    obj.location = this.data.location;
    obj.employmentType = this.data.employmentType.value;
    obj.userHrId = getApp().globalData.userId;
      resolve(obj);
    })

  },

  onPublishPositoin() {
      this.getPublishValue().then((obj) => {
        // 小时工职位流程  新增-支付-发布
        this.onCreatePos(obj);
      })
  },

  /**
   * 提交退款申请
   */
  onSubmitRefund() {
    let param = {
      token: token
    }
    console.log(param);
    T.req({
      loadTitle: '提交中...',
      url: config.api + 'pay/wechat/refund?' + T.param(param),
      method: 'POST',
      data: {
        refundFee: this.data.residueMoney,
        outTradeNo: this.data.redpacketOrderId
      },
      success: (res) => {
        T.toast({ id: '#toast', text: '申请成功', success: () => {
          wx.navigateBack({
            delta: 1
          })
        } });
      }
    })
  },

  /**
   * 显示退款信息
   */
  onRefund(e) {
    T.req({
      url: config.api + 'center/userinfo',
      method: 'GET',
      data: {
        token: token
      },
      success: (res) => {
        this.setData({
          refundMethod: res.name,
          refundMoney: Number(this.data.residueMoney),
          isShowRefundShade: true,
        });
      }
    })
  
  },

  onHideRefundShade() {
    this.setData({ isShowRefundShade: false });
  },

  /**
   * 下架
   */
  onSoldOut() {
    let param = {
      token: token,
      id: this.data.positionEditId
    }
    T.req({
      loadTitle: '请求中...',
      url: config.api + 'position_hourly/soldout?' + T.param(param),
      method: 'PUT',
      success: (res) => {
        T.toast({ id: '#toast', text: '下架成功', success: () => {
          this.onHourlySucessChange();
        } });
      }
    })
  },

  /**
   * 编辑(更新)
   */
  onEditPosition() {
    this.getPublishValue().then((obj) => {
      let _temObj = {};
      if (obj.employmentType == 1) {
        _temObj.workCompanyId = obj.workCompanyId;
        _temObj.workCompany = obj.workCompany;
        _temObj.entrustPhoto = obj.entrustPhoto
      } else {
        _temObj.workCompany = '';
      }
      T.req({
        loadTitle: '请求中...',
        url: config.api + 'position_hourly?token=' + token,
        method: 'PUT',
        data:{
          positionHourlyId: Number(this.data.positionEditId),
          userHrId: getApp().globalData.userId,
          positionName: obj.positionName,
          salary: obj.salary,
          clearingWay: obj.clearingWay,
          startDate: obj.startWorkDate,
          endDate: obj.endWorkDate,
          startWorkTime: obj.startWorkTime,
          endWorkTime: obj.endWorkTime,
          candidateRequireId: obj.candidateRequireId,
          education: obj.education,
          street: obj.street,
          address: obj.address,
          location: obj.location,
          description: obj.description,
          employmentType: obj.employmentType,
          ..._temObj
        },
        success: (res) => {
          if (this.data.isUpdatePay) { // 是否有新的支付设置
            this.onPay().then(orderId => {
              payStatus(orderId).then(() => {
                T.toast({
                  id: '#toast', text: '编辑成功', success: () => {
                  this.onHourlySucessChange();
                  }
                });
              });
            })
          } else { // 没有更改支付内容，直接编辑
            T.toast({
              id: '#toast', text: '编辑成功', success: () => {
                  this.onHourlySucessChange();
              }
            });
          }
        }
      })
    })
  },

  onRedpackDesc() {
    wx.navigateTo({
      url: '/pages/rule-state/redpack/index',
    })
  }
})